// pages/group/group-edit.js
var util = require('../../utils/util.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showTopTips: false,
    topTipTxt: null,
    groupInfo: {
      name: "",
      endDate: util.formatDate(new Date()),
      description: "",
      headFile: "",
      headImg: null
    },
    location:{
      name:"",
      address:""
    },
    goodsList: [{
      name: "",
      headImg: null,
      headFile: "",
      price: null,
      unit: "",
      totalNum: null
    }],
    imgWidth: 0,
    imgHeight: 0
  },
  bindDateChange: function(e) {
    var name=e.currentTarget.dataset.name;
    var data={};
    data[name] = e.detail.value;
    this.setData(data)
  },
  valueChange: function(e) {
    var value = e.detail.value;
    var name = e.currentTarget.dataset.cname;
    var d = {};
    d[name] = value;
    this.setData(d);
  },
  validate: function() {
    if (util.isBlank(this.data.groupInfo.name)) {
      util.showTopTips("团购标题不能为空");
      return false;
    }
    if (util.isBlank(this.data.groupInfo.endDate)) {
      util.showTopTips("截止日期不能为空");
      return false;
    }
    if (util.isBlank(this.data.groupInfo.description)) {
      util.showTopTips("团购内容不能为空");
      return false;
    }
    //数据修改不用验证图片
    if (util.isBlank(this.data.groupInfo.headImg) && !this.data.groupInfo.groupId) {
      util.showTopTips("团购图片不能为空");
      return false;
    }
    for (var i = 0; i < this.data.goodsList.length; i++) {
      if (util.isBlank(this.data.goodsList[i].name)) {
        util.showTopTips("物品名称不能为空");
        return false;
      }
      if (util.isBlank(this.data.goodsList[i].price)) {
        util.showTopTips("价格不能为空");
        return false;
      }
      if (util.isBlank(this.data.goodsList[i].unit)) {
        util.showTopTips("单位不能为空");
        return false;
      }
      if (util.isBlank(this.data.goodsList[i].totalNum)) {
        util.showTopTips("总库存不能为空");
        return false;
      }
      //数据修改不用验证图片
      if (util.isBlank(this.data.goodsList[i].headImg) && !this.data.groupInfo.groupId) {
        util.showTopTips("物品图片不能为空");
        return false;
      }
    }
    if (util.isBlank(this.data.location.address)) {
      util.showTopTips("取货地点不能为空");
      return false;
    }
    return true;
  },
  getData: function(groupid) {
    var that = this;
    util.gets({
      uri: '/group/group/info/' + groupid,
      success: function(r) {
        that.setData({
          "groupInfo": r.group.solitaire,
          "goodsList": r.group.goodsList,
          "location":r.group.location
        });
      }
    });
    
  },
  saveOrUpdate: function() {
    var groupInfo = this.data.groupInfo;
    if (groupInfo.groupId && groupInfo.status != '0') {
      wx.showModal({
        content: '已经过期，不能修改',
        showCancel: false,
      })
      return;
    }
    if (!this.validate()) {
      return;
    }
    var groupInfo = this.data.groupInfo;
    groupInfo.goodsList = this.data.goodsList;
    
    wx.showLoading({
      title: '处理中',
      icon: 'loading',
    });

    var headers=util.getHeader(app);
    var that = this;
    wx.request({
      url: app.globalData.apiUri +'/group/group/save',
      method:'POST',
      header: headers,
      data: groupInfo,
      success (res){
        var rd=res.data;
        if (rd.code == 0) {
          if(rd.images && rd.images.length>0){
            that.uploadImage(rd.images, 0);
          }else{
            that.saveComplete();
          }
        } else {
          wx.hideLoading();
          util.showTopTips(rd.msg);
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  saveComplete:function(){
    var pages = getCurrentPages();
    //关闭等待框
    wx.hideLoading();
    wx.showModal({
      content: '数据保存成功',
      showCancel: false,
      success: function (res) {
        wx.switchTab({
          url: '../solitaire/record-list',
          success: function (e) {
            var page = getCurrentPages().pop();
            if(page){
              page.setData({ "activeIndex": 1})
              page.getData();
            }
          }
        })
        pages[pages.length - 2].reloadData();
        wx.navigateBack({
          delta: 1
        })
      }
    });
  },
  /**
   * 上传图片
   */
  uploadImage:function(images,index){
    var image = images[index];
    var that=this;
    var add="Y";
    if (this.data.groupInfo.groupId && this.data.groupInfo.groupId>0){
      add = "N";
    }
    var headers = util.getHeader(app);
    wx.uploadFile({
      url: app.globalData.apiUri + '/group/group/uploadImage',
      header: headers,
      filePath: image.headImg,
      name: 'headImg',
      formData: {
        'rowId': image.rowId,
        'tableType': image.tableType,
        'add': add
      },
      complete:function(){
        //图片全部传完
        if (index == images.length - 1) {
          that.saveComplete();
        }
      },
      success(res) {
        const data = res.data
        //未传完，继续递归上传
        if (index < images.length - 1) {
          that.uploadImage(images, index + 1);
        }
      },
      fail(e){
        console.log(e);
      }
    })
  },
  chooseImage: function(e) {
    var key = e.currentTarget.dataset.ikey;
    var that = this;

    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['compressed'], // 指定只能为压缩图，首先进行一次默认压缩
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(photo) {
        console.log(photo.tempFilePaths[0]) //最终图片路径
        //-----返回选定照片的本地文件路径列表，获取照片信息-----------
        wx.getImageInfo({
          src: photo.tempFilePaths[0],
          success: function(imgRes) {
            //---------利用canvas压缩图片--------------
            var ratio = 2;
            var canvasWidth = imgRes.width //图片原始长宽
            var canvasHeight = imgRes.height
            while (canvasWidth > 500 || canvasHeight > 500) { // 保证宽高在400以内
              canvasWidth = Math.trunc(imgRes.width / ratio)
              canvasHeight = Math.trunc(imgRes.height / ratio)
              ratio++;
            }
            that.setData({
              imgWidth: canvasWidth,
              imgHeight: canvasHeight
            })

            //----------绘制图形并取出图片路径--------------
            var ctx = wx.createCanvasContext('canvas')
            ctx.clearRect(0, 0, canvasWidth, canvasHeight);
            ctx.drawImage(imgRes.path, 0, 0, canvasWidth, canvasHeight);
            ctx.draw(false, function(drawRes){
              wx.canvasToTempFilePath({
                canvasId: 'canvas',
                destWidth: canvasWidth,
                destHeight: canvasHeight,
                success: function (tmpRes) {
                  that.setImageUrl(key, tmpRes.tempFilePath);
                },
                fail: function (e) {
                  //第一次失败，可能是绘图未完成，重试一次
                  console.error("出错重试："+e.errMsg);
                  setTimeout(function(){
                    wx.canvasToTempFilePath({
                      canvasId: 'canvas',
                      destWidth: canvasWidth,
                      destHeight: canvasHeight,
                      success: function (tmpRes2) {
                        that.setImageUrl(key, tmpRes2.tempFilePath);
                      },
                      fail: function (e2) {
                        console.error("出错2次了，没办法了");
                      }
                    })
                  },100);
                }
              })
            });
            
          }
        })
      }
    })

  },
  //图片转base64
  setImageUrl: function(key, url) {
    //缓存图片路径
    var urlKey = null;
    if (key == -1) {
      urlKey = "groupInfo.headImg";
    } else {
      urlKey = "goodsList[" + key + "].headImg";
    }
    var setUrl = {};
    setUrl[urlKey] = url;
    this.setData(setUrl);
  },
  previewImage: function(e) {
    var key = e.currentTarget.dataset.ikey;
    var urlList = [];
    if (key == -1) {
      urlList[0] = this.data.groupInfo.headImg;
    } else {
      urlList[0] = this.data.goodsList[key].headImg;
    }
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: urlList // 需要预览的图片http链接列表
    })
  },
  newGoods: function() {
    var data = this.data.goodsList.concat({
      name: "",
      price: null,
      unit: "",
      totalNum: null
    });
    this.setData({
      goodsList: data
    });
  },
  chooseLocation:function(){
    var toUrl ="/pages/my/location";
    if (this.data.location && this.data.location.locationId){
      toUrl = toUrl + "?selectId=" + this.data.location.locationId;
    }
    wx.navigateTo({
      url: toUrl,
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '发布团购接龙',
    })
    if (options.groupId) {
      var groupid = options.groupId;
      this.getData(groupid);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})